package com.gzc.just.play.last.war.common.share.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.jpa.JpaTransactionManager;
import java.util.Arrays;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.PlatformTransactionManager;

import javax.sql.DataSource;
import java.util.Properties;

/**
 * SQLite数据源配置
 * 为All-in-One开发模式提供SQLite数据库支持
 */
@Configuration
@Profile("dev-all-in-one")
@EnableJpaRepositories(
    basePackages = "com.gzc.just.play.last.war.centralserver",
    entityManagerFactoryRef = "entityManagerFactory",
    transactionManagerRef = "transactionManager"
)
public class SQLiteDataSourceConfig {
    
    private static final Logger logger = LoggerFactory.getLogger(SQLiteDataSourceConfig.class);
    
    @Value("${sqlite.database.path:./data/dev.db}")
    private String databasePath;
    
    @Value("${sqlite.show-sql:false}")
    private boolean showSql;
    
    @Value("${sqlite.format-sql:true}")
    private boolean formatSql;
    
    /**
     * SQLite数据源配置
     */
    @Bean
    public DataSource dataSource() {
        logger.info("init SQLite db,db file path: {}", databasePath);
        
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName("org.sqlite.JDBC");
        dataSource.setUrl("jdbc:sqlite:" + databasePath);
        
        // SQLite连接属性
        Properties connectionProperties = new Properties();
        connectionProperties.setProperty("foreign_keys", "true");
        connectionProperties.setProperty("journal_mode", "WAL");
        connectionProperties.setProperty("synchronous", "NORMAL");
        
        dataSource.setConnectionProperties(connectionProperties);
        
        return dataSource;
    }
    
    /**
     * JPA实体管理器工厂配置
     */
    @Bean
    public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
        LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
        em.setDataSource(dataSource());
        String[] packagesToScan = new String[] {
            "com.gzc.just.play.last.war.centralserver.model",
            "com.gzc.just.play.last.war.centralserver.user.model",
            "com.gzc.just.play.last.war.centralserver.guild.model",
            "com.gzc.just.play.last.war.centralserver.quest.model",
            "com.gzc.just.play.last.war.centralserver.inventory.model",
            "com.gzc.just.play.last.war.centralserver.character.model",
            "com.gzc.just.play.last.war.sceneserver.entity",
            "com.gzc.just.play.last.war.sceneserver.battle.model"
        };
        logger.info("Configuring SQLite EntityManagerFactory with packages: {}", Arrays.toString(packagesToScan));
        em.setPackagesToScan(packagesToScan);
        
        HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
        em.setJpaVendorAdapter(vendorAdapter);
        
        Properties jpaProperties = new Properties();
        jpaProperties.setProperty("hibernate.dialect", "org.hibernate.community.dialect.SQLiteDialect");
        jpaProperties.setProperty("hibernate.hbm2ddl.auto", "update");
        jpaProperties.setProperty("hibernate.show_sql", String.valueOf(showSql));
        jpaProperties.setProperty("hibernate.format_sql", String.valueOf(formatSql));
        jpaProperties.setProperty("hibernate.use_sql_comments", "true");
        jpaProperties.setProperty("hibernate.jdbc.batch_size", "20");
        jpaProperties.setProperty("hibernate.order_inserts", "true");
        jpaProperties.setProperty("hibernate.order_updates", "true");
        
        // SQLite特定配置
        jpaProperties.setProperty("hibernate.connection.foreign_keys", "true");
        jpaProperties.setProperty("hibernate.connection.journal_mode", "WAL");
        jpaProperties.setProperty("hibernate.connection.synchronous", "NORMAL");
        
        em.setJpaProperties(jpaProperties);
        
        return em;
    }
    
    /**
     * 事务管理器配置
     */
    @Bean
    public PlatformTransactionManager transactionManager() {
        JpaTransactionManager transactionManager = new JpaTransactionManager();
        transactionManager.setEntityManagerFactory(entityManagerFactory().getObject());
        return transactionManager;
    }
    
    /**
     * 初始化数据库
     */
    @Bean
    public SQLiteDatabaseInitializer databaseInitializer() {
        return new SQLiteDatabaseInitializer();
    }
    
    /**
     * SQLite数据库初始化器
     */
    public static class SQLiteDatabaseInitializer {
        
        private static final Logger logger = LoggerFactory.getLogger(SQLiteDatabaseInitializer.class);
        
        public SQLiteDatabaseInitializer() {
            logger.info("SQLiteDatabaseInitializer created");
            // 这里可以添加数据库初始化脚本
            // 例如：创建必要的表结构、初始化数据等
        }
        
        /**
         * 执行数据库初始化脚本
         */
        public void initialize() {
            logger.info("SQLite initialize over");
        }
    }
}